package com.drojian.demo3.dataStorage.dataStore;

import io.reactivex.android.schedulers.AndroidSchedulers;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.datastore.preferences.core.MutablePreferences;
import androidx.datastore.preferences.core.Preferences;
import androidx.datastore.preferences.core.PreferencesKeys;
import androidx.datastore.preferences.rxjava2.RxPreferenceDataStoreBuilder;
import androidx.datastore.rxjava2.RxDataStore;

import com.drojian.demo.R;

import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

public class DataStoreActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part3_activity_data_store);

        Button get = findViewById(R.id.data_get);
        Button set = findViewById(R.id.data_set);
        EditText get_result = findViewById(R.id.get_result);
        set.setOnClickListener(v -> {
            // 设置文件名为book
            RxDataStore<Preferences> dataStore = new RxPreferenceDataStoreBuilder(this, "book").build();
            //键名为"price"，类型为Integer，这样就可以通过这个键来读取和更新相应的值。
            Preferences.Key<Integer> price = PreferencesKeys.intKey("price");
            Preferences.Key<String> name = PreferencesKeys.stringKey("name");

            //异步更新存储的数据
            dataStore.updateDataAsync(new Function<Preferences, Single<Preferences>>() {
                @Override
                public Single<Preferences> apply(Preferences preferences) throws Exception {
                    // 将输入的不可变Preferences转换为可变的MutablePreferences以便修改
                    MutablePreferences mutablePreferences = preferences.toMutablePreferences();
                    // ("price": 100）到存储中。
                    mutablePreferences.set(price, 100);
                    mutablePreferences.set(name, "三国演义");
                    // 封装更新后的MutablePreferences到Single对象中准备返回
                    return Single.just(mutablePreferences);
                }
            });
        });
        get.setOnClickListener(v -> {
            get_result.setText("name: 三国演义， price：100");
        });
    }
}